const Koa = require('koa2');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser')
const jwt = require('jsonwebtoken')
const {query} = require("./utils/db");
const cors = require('koa2-cors');
const dayjs = require("dayjs");
const app = new Koa();
const router = new Router();
const port = 5050;

// // 配置 CORS
// app.use(cors({
// 	origin: '*',
// 	exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
// 	maxAge: 5, // 预检请求的有效时间
// 	credentials: true, // 允许携带 Cookie
// 	allowMethods: ['GET', 'POST'], // 允许的 HTTP 方法
// 	allowHeaders: ['Content-Type', 'Authorization', 'Accept'] // 允许的请求头
// }));
// app.use(cors())

router.use(bodyParser())
router.post('/api/login', async (ctx)=>{
	try{

		let {username, password} = ctx.request.body;
		let mydata = await new Promise((resolve, reject) => {
			// 访问数据库,拿到数据返回给前端
			let sql = `select * from user where username='${username}' and password='${password}' Limit 1`;
			query(sql, (err, data) => {
				if (err) throw err;
				// 对数据进行处理 eg:
				resolve(data)
			})
		})
		if(mydata.length === 1){
			const token = jwt.sign({ username, password }, 'secret', { expiresIn: 3600 })
			ctx.body = {
				code: 200,
				data: {token},
				msg: '登录成功'
			};
		}else{
			ctx.body = {
				code:-1,
				msg: '用户名或密码错误'
			}
		}
	}catch (e) {
		ctx.body = {
			code: -1,
			msg: e
		}
	}
})

router.get('/api/recordList', async (ctx)=>{
	try{
		let res = await new Promise((resolve, reject) => {
			let {orderNum, alipayRealName,tel} = ctx.query;
			console.log( ctx.query)
			// 访问数据库,拿到数据返回给前端
			let sql = 'select * from record where 1=1';
			if(orderNum){
				sql += ` and orderNum='${orderNum}'`;
			}
			if(alipayRealName){
				sql += ` and alipayRealName='${alipayRealName}'`;
			}
			if(tel){
				sql += ` and tel='${tel}'`;
			}

			console.log(sql)
			query(sql, (err, data) => {
				if (err) throw err;
				// 对数据进行处理 eg:
				resolve(data)
			})
		})
		ctx.body = {
			code: 200,
			data: res,
			msg: '获取成功'
		};
	}catch (e){
		ctx.body = {
			code: -1,
			msg: '获取失败'
		}
	}
})

router.post('/api/addRecord', async (ctx)=>{
	try{
		let {orderNum,
			goods,
			costPrice,
			alipayAccount,
			alipayRealName,
			tel
		} = ctx.request.body;
		if(!goods){
			ctx.body = {
				code: -1,
				msg: '酒水不能为空'
			}
			return
		}
		//
		if(!alipayAccount){
			ctx.body = {
				code: -1,
				msg: '支付宝账号不能为空'
			}
			return
		}
		//alipayRealName
		if(!alipayRealName){
			ctx.body = {
				code: -1,
				msg: '支付宝姓名不能为空'
			}
			return
		}

		// 转浮点数
		costPrice = parseFloat(costPrice)
		if(!costPrice){
			ctx.body = {
				code: -1,
				msg: '成本价格式不正确'
			}
			return
		}
		// tel转整型
		if( tel.length !== 11){
			ctx.body = {
				code: -1,
				msg: '手机格式不正确'
			}
			return
		}
		let res = await new Promise((resolve, reject) => {
			// 访问数据库,拿到数据返回给前端
			let sql = `insert into record(orderNum, goods, costPrice, alipayAccount, alipayRealName, tel,createdTime) values('${orderNum}', '${goods}', '${costPrice}', '${alipayAccount}', '${alipayRealName}', '${tel}','${dayjs().format('YYYY-MM-DD HH:mm:ss')}')`
			console.log(sql)
			query(sql, (err, data) => {
				if (err) throw err;
				// 对数据进行处理 eg:
				resolve(data)
			})
		})
		if(res){
			ctx.body = {
				code: 200,
				msg: '添加成功'
			}
		}
	}catch (e){
		ctx.body = {
			code: -1,
			msg: '添加失败'
		}
	}
})


app.use(router.routes(), router.allowedMethods());

app.listen(port, ()=>{
	console.log('Server is running at http://localhost:'+port);
})

